package com.yulang.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yulang.server.mapper.SectionMapper;
import com.yulang.server.pojo.Course;
import com.yulang.server.pojo.Section;
import com.yulang.server.service.CourseService;
import com.yulang.server.service.SectionService;
import com.yulang.server.utils.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 小节 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2020-04-25
 */
@Service
public class SectionServiceImpl extends ServiceImpl<SectionMapper, Section> implements SectionService {

    @Autowired
    private CourseService courseService;

    @Transactional
    @Override
    public void saveSection(Section section) {
        section.setId(UuidUtil.getShortUuid());
        this.save(section);
        QueryWrapper<Section> query = new QueryWrapper<>();
        query.eq(Section.COURSE_ID,section.getCourseId());
        List<Section> list = this.list(query);
        AtomicReference<Integer> time = new AtomicReference<>(0);
        list.forEach(item->{
            time.updateAndGet(v -> v + item.getTime());
        });
        UpdateWrapper<Course> update = new UpdateWrapper<>();
        update.set(Course.TIME,time.get());
        update.eq(Course.ID,section.getCourseId());
        courseService.update(update);
    }
}
